package InetAgreement;

import java.nio.charset.Charset;

import Tools.Log;
import XML.XMLNode;

/**
 * 通信数据封包协议
 * 
 * 数据包格式： @ 数据长度 数据内容 数据效验长度 例：@000029<login uid="SkyWind" pwd=""/>000029
 * 
 * 前后的000029表示数据的长度
 * 
 * @author Sky.Wind
 * 
 */
public class InetDataEncapsulation {

	public static final char DATA_HEAD = '@';// 包头 @

	public static void main(String[] args) {
		InetDataEncapsulation d = new InetDataEncapsulation();
		String data = d.Package("</>");
		System.out.println(Charset.defaultCharset());
		StringBuffer buf = new StringBuffer("@00135<update gucode=\"13\" cmd=\"get\" gcode=\"79\" value=\"我是谁,我是我,sky,男,1341100900000,旅游其它,A,,1,萍乡,yiyongpeng@tom.com,手动阀上的 ,\" userid=\"skywind\"/>00135");
		System.out.println(d.baleBreaking(buf));
	}

	/**
	 * 数据流解包
	 * 
	 * @param data
	 *            待解包数据流缓冲，自动移除解包成功的字符串
	 * @return 解包成功的数据
	 */
	public String baleBreaking(StringBuffer data) {
		String str = null;
		if (data.length() > 11) {
			if (data.charAt(0) == DATA_HEAD) {
				int slength = 0;
				int elength = 0;
				try {
					slength = Integer.parseInt(data.substring(1, 6));// 获得包长
					if (data.length() >= slength + 11) {
						elength = Integer.parseInt(data.substring(slength + 6, slength + 11));
						if (slength == elength) {
							str = data.substring(6, 6 + slength);
							str = XMLNode.unReplaceLineChar(str);
						} else {
							Log.print("Pack-error: "+elength+" - "+slength);
						}
					}else{
						Log.print("Pack-length: "+data.length()+" / "+(slength + 11));
					}
				} catch (Exception e) {
					slength = data.indexOf("@", slength != 0 ? slength + 11 : 1);
					slength = slength == -1 ? data.length() : slength;
					slength -= 11;
					elength = 1;// 标记删除废包
				} finally {
					if (elength != 0){
						data.delete(0, slength + 11);
					}
				}
			} else {
				int i = data.indexOf("@");
				data.delete(0, i != -1 ? i : data.length());
				Log.print("Pack-error: head is'nt '@'");
			}
		}
		return str;
	}

	/**
	 * 数据封包
	 * 
	 * @param Data
	 *            待封包数据，长度 <= 65535个字符
	 * @return
	 */
	public String Package(String Data) {
		Data = XMLNode.replaceLineChar(Data);
		StringBuffer sb = new StringBuffer("@");
		String length = Strlength(Data.length(), 5);
		return sb.append((length)).append(Data).append(length).toString();
	}

	private String Strlength(int number, int size) {
		StringBuffer num = new StringBuffer(String.valueOf(number));
		for (int i = num.length(); i < size; i++) {
			num.insert(0, "0");
		}
		return num.toString();
	}
}
